// tion for singly-linked list.
#include <stack>
#include <iostream>
#include <stdio.h>
using namespace std;

struct ListNode {
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* result_listnode = new ListNode(-1);
            ListNode* result_head = result_listnode;
            bool carry = false;
            while (l1 != NULL || l2 != NULL || carry) {
                if (l1 != NULL && l2 != NULL) {
                    int result_val = l1->val + l2->val;
                    l1 = l1->next;
                    l2 = l2->next;
                    carry = this->calculate(carry, result_val, result_listnode);
                } else if (l1 != NULL) {
                    int result_val = l1->val ;
                    l1 = l1->next;
                    carry = this->calculate(carry, result_val, result_listnode);
                } else if (l2 != NULL) {
                    int result_val = l2->val ;
                    l2 = l2->next;
                    carry = this->calculate(carry, result_val, result_listnode);
                } else {
                    if (carry) {
                        result_listnode->next = new ListNode(1);
                    } 
                    break; 
                }
            }
            result_listnode = result_head->next;
            delete result_head;
            return result_listnode;  
        }
        bool inline calculate(bool carry, int result_val, ListNode* &result_listnode) {
            //cout << "result_val:" << result_val << endl;
            if (carry) {
                ++result_val;
            }
            if (result_val > 9) {
                result_val -= 10;
                carry = true;
            } else {
                carry = false; 
            }
            result_listnode->next = new ListNode(result_val);
            cout << "before:" << result_listnode->val<< "\tresult=" << result_listnode->next->val << endl;
            result_listnode = result_listnode->next;
            return carry;
        }
};
int main() {
    ListNode node1(7);
    ListNode node2(8);
    Solution solu;
    ListNode* resultNode = solu.addTwoNumbers(&node1, &node2);
    while (resultNode) {
        cout << resultNode->val << endl;
        resultNode = resultNode->next;
    }
    //stack<ListNode*> stack_listnode;
    //stack_listnode.push(&node1);
    //stack_listnode.push(&node2);
    //ListNode* top = stack_listnode.top();
    //cout << top->val << endl;    
    return 0;
}
